package com.sykuku.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sykuku.common.BaseContext;
import com.sykuku.controller.expection.BusinessException;
import com.sykuku.dao.AddressBookMapper;
import com.sykuku.dao.OrderMapper;
import com.sykuku.dao.ShoppingCartMapper;
import com.sykuku.dao.UserMapper;
import com.sykuku.dto.OrderPageConditionDto;
import com.sykuku.pojo.*;
import com.sykuku.service.OrderDetailService;
import com.sykuku.service.OrderService;
import com.sykuku.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.*;


@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 用户下单
     * @param orders
     * A. 获得当前用户id, 查询当前用户的购物车数据
     * B. 根据当前登录用户id, 查询用户数据
     * C. 根据地址ID, 查询地址数据
     * D. 组装订单明细数据, 批量保存订单明细
     * E. 组装订单数据, 批量保存订单数据
     * F. 删除当前用户的购物车列表数据
     */
    @Override
    public void submit(Orders orders) {
        //查询用户的购物车数据
        Long userID = BaseContext.getThreadLocalID();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userID);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new BusinessException(1,"购物车为空，不能下单");
        }

        //查询用户数据
        User user = userMapper.selectById(userID);

        //查询用户的地址数据
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        if(addressBook == null){
            throw new BusinessException(1,"用户地址信息有误，不能下单");
        }

        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);

        //把shoppingCart添加到orderDetail表中
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((shoppingCart) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());

            BigDecimal itemAmount = shoppingCart.getAmount();//单价
            BigDecimal bigDecimal = new BigDecimal(shoppingCart.getNumber());//数量
            BigDecimal result = itemAmount.multiply(bigDecimal);//相乘总金额
            int intValue = result.intValue();//该方法将指定数字的值作为int返回

            amount.addAndGet(intValue);

            return orderDetail;
        }).collect(Collectors.toList());

        //把order数据添加至order表单中
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userID);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        String proName=addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName();
        String cname=addressBook.getCityName() == null ? "" : addressBook.getCityName();
        String dname=addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName();
        String details=addressBook.getDetail() == null ? "" : addressBook.getDetail();
        orders.setAddress(proName+cname+dname+details);
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);


        //清空购物车数据
        shoppingCartService.remove(wrapper);



    }

    @Override
    public Page<Orders> orderSelecetPage(OrderPageConditionDto dto) {
        Page<Orders> ordersPage = new Page<>(dto.getPage(),dto.getPageSize());
        Page<Orders> page = baseMapper.orderPage(ordersPage,dto);
        return page;
    }
}